<template>
    <Card dis-hover :bordered="false">
        <Form inline>
            <FormItem>
                <Button @click="handleAdd" type="primary" v-hasC="{ name: 'v1-project-role-add', flag: 'v1/project/role/add'}">新增</Button>
            </FormItem>
        </Form>
        <Table :columns="columns" :data="list" :loading="loading" border v-hasC="{ name: 'v1-project-role-list', flag: 'v1/project/role/list'}">
            <template #status="{row}">
                <Badge v-if="+row.status === 1" status="success" text="正常" />
                <Badge v-else status="error" text="停用" />
            </template>
            <template #action="{row}">
            <a @click="handleEdit(row)" v-hasC="{ name: 'v1-project-role-edit', flag: 'v1/project/role/edit'}">编辑</a>
            <Divider type="vertical" v-hasC="{ name: 'v1-project-role-del', flag: 'v1/project/role/del'}"/>
            <a @click="handleDelete(row)" class="fontColor"  v-hasC="{ name: 'v1-project-role-del', flag: 'v1/project/role/del'}">删除</a>
            </template>
        </Table>
         <div class="ivu-mt ">
            <Page
              :total="total"
              :current.sync="current"
              show-total
              show-elevator
              :page-size="pageSize"
              @on-change="handleChangeSize"
              :page-size-opts="pageOpts"
              show-sizer
              @on-page-size-change="changePageSize"
              v-hasC="{ name: 'v1-project-role-list', flag: 'v1/project/role/list'}"
            />
          </div>
        <Modal :mask-closable="false" v-model="personModal" :title="edit?'新增':'编辑'"  width="560"  @on-cancel='handleCancel' >
            <Form ref="formvaild" :model="formData" :rules="ruleValidate" :label-width="100" >
                <FormItem label="角色名称" prop="name">
                    <Input placeholder="请输入角色名称"  v-model="formData.name"/>
                </FormItem>
                <FormItem label="说明" prop="desc">
                    <Input placeholder="请输入说明"  type="textarea" :autosize="{minRows: 2,maxRows: 5}" v-model="formData.desc"/>
                </FormItem>
                <!-- <FormItem label="排序">
                    <InputNumber :min="1" v-model="formData.sort" />
                </FormItem> -->
                <FormItem label="权限">
                    <Tree :data="data" show-checkbox  ref="roleTree"   multiple  @on-check-change="handleSelectRoles"></Tree>
                </FormItem>
                <FormItem label="状态">
                     <Switch v-model="formData.status">
                        <span slot="open">开启</span>
                        <span slot="close">关闭</span>
                    </Switch>
                </FormItem>
            </Form>
             <template #footer>
                <Button @click="handleCancel">取消</Button>
                <Button type="primary" @click="handleSubmit" :loading="modalLoading">确定</Button>
            </template>
        </Modal>
    </Card>
    </template>
    <script>
        import {agencyList ,roleInfo,agencyUpdateRole,agencyRoleDel}from '@/api/role.js'
        export default {
            name: 'role',
            data () {
                return {
                    loading:false,
                    edit:true,
                    personModal:false,
                    modalLoading:false,
                    total:0,
                    pageSize:10,
                    current:1,
                    pageOpts:[10,20,30,50],
                    data: [],
                    columns:[
                        {
                            key:'name',
                            title:'角色名称',
                            width:150
                        },
                     
                        {
                            key:'desc',
                            title:'说明',
                            minWidth:150,
                            tooltip:true

                        },
                        {
                            slot:'status',
                            title:'状态',
                            width:150
                        },
                        {
                            key:'created_at',
                            title:'创建时间',
                            width:160
                        },
                        // {
                        //     key:'sort',
                        //     title:'排序',
                        //     minWidth:150
                        // },
                        {
                            slot:'action',
                            title:'操作',
                            width:118
                        }
                    ],
                    list:[],
                    formData:
                       {
                        name:'',
                        status:true,
                        // sort:1,
                        desc:''
    
    
                       },
                    ruleValidate:{
                        name: [
                            { required: true, message: '请输入角色名称',trigger:'blur' }
                        ],
                        desc:[
                            { required: true, message: '请输入角色说明',trigger:'blur' }
                        ],
                    },
                    // 设置权限的集合
                    selectPermissonList: [],
                    id:'',
                };
            },
            mounted() {
                this.getData()
            },
            methods: {
                handleChangeSize(index){
                    this.current=index
                    this.getData()
                },
                changePageSize(val){
                    this.pageSize=val
                    this.getData()
                },
                getData() {
                    this.loading = true
                    const params={
                        page:this.current,
                        pageSize:this.pageSize
                    }
                    agencyList(params).then(res=>{
                        this.list=res.list
                        this.total=res.total
                        this.loading = false
                        
                    })
                },
                //获取角色权限
                getroleInfo(val){
                    roleInfo({id:val}).then(res=>{
                        this.data=res.auth
                    })
                },
                handleSelectRoles(){
                     let checklist = this.$refs[
                    "roleTree"
                    ].getCheckedAndIndeterminateNodes();
                    this.selectPermissonList = [];
                    checklist.forEach((item) => {
                        let resList = {};
                        resList.permission_id = item.value;
                        resList.permission_type = item.permission_type;
                        this.selectPermissonList.push(resList);
                    });
                },
                handleAdd() {
                    this.personModal = true
                    this.edit = true
                    this.getroleInfo('')
                },
                handleEdit(row) {
                    // console.log(row,'row')
                    this.personModal = true
                    this.formData={
                        name:row.name,
                        // sort:row.sort,
                        status:+row.status===1?true:false,
                        desc:row.desc
                    },
                    this.id=row.id
                    this.getroleInfo(row.id)
                    this.edit = false
                },
                handleCancel(){
                    this.$refs.formvaild.resetFields();
                    this.personModal=false
                },
                handleSubmit(){
                    this.$refs.formvaild.validate((valid) => {
                    if (valid) {
                        let menuIds = [];
                    let actionIds = [];
                    let moduleIds = [];
                    if (
                        this.selectPermissonList &&
                        this.selectPermissonList.length > 0
                    ) {
                        this.selectPermissonList.forEach((item) => {
                            if (item.permission_type === 0) {
                                moduleIds.push(item.permission_id);
                            } else if (item.permission_type === 1) {
                                menuIds.push(item.permission_id);
                            } else if (item.permission_type === 2) {
                                actionIds.push(item.permission_id);
                            }
                        });
                    }
                    let sendData = {};
                    // sendData.id = this.isEdit.id;
                    sendData.menu_ids = menuIds.length > 0 ? menuIds.join(",") : "";
                    sendData.action_ids =
                        actionIds.length > 0 ? actionIds.join(",") : "";
                    sendData.module_ids =
                        moduleIds.length > 0 ? moduleIds.join(",") : "";
                     sendData.status = this.formData.status === true ? "1" : "0";
                     sendData.name=this.formData.name
                    //  sendData.sort=this.formData.sort
                     sendData.desc=this.formData.desc
                     if(this.edit){
                         agencyUpdateRole(sendData).then(res=>{                             
                        this.$Message.success('新增成功')
                        this.personModal=false
                        this.getData()
                     })
                     }else{
                        agencyUpdateRole(Object.assign({},sendData,{id:this.id})).then(res=>{
                            this.$Message.success('编辑成功')
                             this.personModal=false
                            this.getData()
                        })
                     }
                    } 
                })
              
                    
                    },
                handleDelete(row) {
                    this.$Modal.confirm({
                        title:'删除提示',
                        content:'是否确认删除，删除后将无法恢复，已绑定的数据将解除绑定，删除前建议先做类型迁移',
                        onOk:()=> {
                            agencyRoleDel({id:row.id}).then(res=>{
                                this.$Message.success('删除成功')
                                this.getData()
                            })
                            
                        }
                    }) 
                },
               
            },
           
        };
    </script>
    <style lang='less'>
    .fontColor {
        color:rgb(223, 7, 7);
    }
    .active{
        color: #ccc ;
        cursor: not-allowed;
        pointer-events: none;
    }
    .spanstyle{
        color: #f00;
            cursor: pointer;
    }
    </style>